package com.czy.utilslib.viewModel;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;

import io.reactivex.disposables.CompositeDisposable;

public class BaseViewModel extends ViewModel {

    protected CompositeDisposable disposables;

    public BaseViewModel() {
        disposables = new CompositeDisposable();
    }

    protected <T> BaseMutableLiveData<T> getLiveData(BaseMutableLiveData<T> liveData) {
        if (liveData == null) {
            liveData = new BaseMutableLiveData<>();
        }
        return liveData;
    }

    public <T> void observe(BaseMutableLiveData<T> liveData, LifecycleOwner owner, Observer<T> observer, Lifecycle lifecycle){
        liveData.observe(owner, data->{
            try {
                observer.onChanged(data);
            } catch (NullPointerException npe) {
                // 处理数据为null的情况
                Log.e("LiveDataObserver", "Data is null while handling LiveData change", npe);
            } catch (Exception e) {
                // 其他异常处理
                Log.e("LiveDataObserver", "Error while handling LiveData change: " + e.getMessage(), e);
            }
        });

        lifecycle.addObserver(new DefaultLifecycleObserver() {
            // 销毁
            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onDestroy(owner);
                liveData.removeObserver(observer);
            }

            // 停止
            @Override
            public void onStop(@NonNull LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onStop(owner);
                liveData.removeObserver(observer);
            }
        });
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        disposables.clear();
    }

}
